<template>
    <div class="publish-menu">
        <nav-header>
			<template slot="menuBefore">
				<li><router-link to="/life/canteen/menu-list" tag="a">菜单管理</router-link></li>
				<li class="gap">&gt;</li>
			</template>
            <li v-if="idEdit">编辑菜单</li>
		</nav-header>

        <div class="publish-container" v-loading="loading.status" :element-loading-text="loading.txt">
            <el-form 
                :model="addForm" 
                :rules="rules" 
                ref="addForm" 
                label-width="130px" 
                class="add-form" 
                label-position="left">
                <el-form-item label="日期：" prop="dayTime">
                    <el-date-picker
                        v-model="addForm.dayTime"
                        type="date"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期"
                        @change="varDayTime"
                        style="width:300px">
                    </el-date-picker>
                    <div v-if="hadTime" class="el-form-item__error">当前日期已存在菜单，请重新设置</div>
                </el-form-item>

                <div v-for="(item, inx) in addForm.mealList" :key="inx">
                    <el-form-item :label="'餐次名称' + (inx + 1)" :prop="'mealList.'+ inx +'.name'" :rules="rules.name">
                        <el-input v-model="item.name" maxlength="10" placeholder="请输入餐次名称，如早餐、午餐、晚餐、宵夜" style="width:300px"></el-input>
                        <span v-if="inx !== 0" @click="delMeal(inx)" style="margin-left:20px;color:#F56C6C;cursor:pointer;">删除</span>
                    </el-form-item>
                    <el-form-item label="添加菜式" class="add-food">
                        <div v-for="(item1, inx1) in item.foods" :key="inx1" class="list-box">
                            <img :src="BASE_URL + item1.path" alt="菜式图片">
                            <span>{{item1.name}}</span>
                            <span>{{item1.price}}元</span>
                            <i class="el-icon-error food-del-btn" @click="delFood(inx, inx1)"></i>
                        </div>
                        <div class="add-food-box" @click="addFood(inx)" v-if="item.foods.length < 20"><i class="el-icon-plus"></i></div>
                    </el-form-item>
                </div>

                <span v-if="addForm.mealList.length < 5" class="add-meal" @click="addMeal"><i class="el-icon-plus"></i>添加餐次</span>
                <el-form-item>
                    <el-button type="primary" @click="resetForm" plain>取消</el-button>
                    <el-button type="primary" @click="submitForm('addForm')">保存</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-dialog 
            title="添加菜式" 
            :visible.sync="foodVisible" 
            class="food-manage" 
            width="800px" 
            :before-close="cancelForm"
            :close-on-click-modal="false">
            <div>
                <div class="food-content-head">
                    <div class="search-text">
						<el-input v-model="listParam.keyword" placeholder="名称、价格" @keyup.enter.native="searchFunc"></el-input>
                        <div>
                            <el-button type="primary" @click="searchFunc">搜索</el-button>
                            <el-button type="primary" @click="resetFood">重置</el-button>
                        </div>
                    </div>
                </div>

                <div class="zh-table-contents">
                    <el-table
                        :data="listData"
                        fixed
                        border
                        ref="multipleTable"
                        max-height="600"
                        :row-key="getRowKeys"
                        @selection-change="tableSelectionChange"
                        style="width: 100%">
                        <el-table-column
                            type="selection"
                            :reserve-selection="true"
                            width="50"
                            align="center"
                            fixed>
                        </el-table-column>
                        <el-table-column
                            prop="name"
                            label="菜式名称"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="price"
                            label="菜式价格"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="create_time"
                            label="创建时间"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                    </el-table>

                    <div class="table-pagination" v-show="totalNumber > 10">
                        <el-pagination
                            @size-change="setCurrentSize"
                            @current-change="setCurrentPage"
                            :current-page="listParam.pageIndex"
                            :page-sizes="[10, 20, 30, 40, 50, 100]"
                            :page-size="listParam.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="totalNumber">
                        </el-pagination>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelForm" plain>取消</el-button>
                <el-button type="primary" @click="submitNewCar">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            activeInx: 0, // 当前餐次
            idEdit: false, // 是否编辑状态
            hadTime: false, // 是否存在日期
            foodVisible: false, // 显示菜式弹窗
            totalNumber: 0,
            meunId: 0,
            selected: [],
            listData: [],
            loading: {
                status: false,
                txt: '保存数据...'
            },
            addForm: {
                dayTime: undefined, // 日期
                mealList: [{
                    id: undefined,
                    name: undefined,
                    foods: []
                }]
            },
            listParam: {
                pageSize: 10,
                pageIndex: 1,
                keyword: undefined
            },
            rules: {
                dayTime: [
                    { required: true, validator: this.validateTime, trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入餐次名称', trigger: ['blur', 'change'] }
                ]
            }
        }
    },
    created() {
        this.idEdit = this.$route.params.id ? true : false;

        if (this.idEdit) {
            this.getInfo();
        }
    },
    watch: {
        'selected'(newVal, oldVal) {
            if (newVal.length > 20) {
                this.selected.length = 20;
            }

            if (newVal.length >= 20) {
                this.nonCheck = true;
            }
        }
    },
    methods: {
        /**
         * 验证日期
         */
        validateTime(rule, value, callback) {
            if (!value) {
                if (this.hadTime) {
                    callback();
                } else {
                    callback(new Error('请选择日期'));
                }
            } else {
                callback();
            }
        },
        /**
         * 获取菜单详情
         */
        getInfo() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;

                if (!is_empty(res.data)) {
                    this.addForm.dayTime = res.data.day_time;
                    this.meunId = res.data.id;
                    this.addForm.mealList = [];

                    res.data.menus.forEach((item, inx) => {
                        let temp = [];

                        item.menu.forEach(item1 => {
                            temp.push({
                                menu_id: item1.id,
                                name: item1.name,
                                price: item1.price,
                                path: item1.path
                            })
                        })

                        this.addForm.mealList.push({
                            id: item.id,
                            name: item.name,
                            foods: temp
                        })
                    })
                }
            })
            const params = {
                day_time: this.$route.params.id
            }

            this.$ajax.get('api/carte/single', {params, func:{success: success}})
        },
        /**
         * 验证日期是否存在
         */
        varDayTime() {
            this.hadTime = false;

            let success = (res => {
               if (!is_empty(res.data)) {
                   this.hadTime = true;
                   this.addForm.dayTime = null;
               }
            })
            const params = {
                day_time: this.addForm.dayTime
            }
            
            this.$ajax.get('api/carte/single', {params, func: {success: success}})
        },
        /**
         * 获取菜式列表
         */
        getFood() {
            let success = (res=>{
                this.listData = res.data.data;
                this.totalNumber = res.data.data_sum;

                this.addForm.mealList[this.activeInx].foods.forEach(item => {
                    this.listData.forEach(val => {
                        if (item.menu_id === val.id) {
                            this.selected.push(val);
                        }
                    })
                })

                let _this = this;
                let _temp = deep_clone(this.selected);

                this.$nextTick(() => {
                    // 不可以使用 clearSelection，否则翻页后，选中的数据会被清空
                    for (let i=0; i<_this.listData.length; i++) {
                        _this.$refs.multipleTable.toggleRowSelection(_this.listData[i], false);
                    }

                    for (let i=0; i<_this.listData.length; i++) {
                        for (let j=0; j<_temp.length; j++) {
                            if (_temp[j].id == _this.listData[i].id) {
                                _this.$refs.multipleTable.toggleRowSelection(_this.listData[i], true);
                            }
                        }
                    }

                    this.selected = _temp; // 重新赋值，否则删除数据后还是会按上次保存的数据
                })
            })
            let params = {
                page_index: this.listParam.pageIndex,
                page_size: this.listParam.pageSize,
                keyword: this.listParam.keyword
            }

            this.$ajax.get('api/carte/menulists', {params, func:{success: success}})
        },
        /**
         * 搜索列表
         */
        searchFunc() {
            this.listParam.pageIndex = 1;
            this.getFood();
        },
        /**
         * 重置菜式列表
         */
        resetFood() {
            this.listParam = {
                pageSize: 10,
                pageIndex: 1,
                keyword: undefined
            }

            this.getFood();
         },
        /**
         * 添加菜式
         */
        addFood(inx) {
            this.foodVisible = true;
            this.activeInx = inx;

            this.resetFood();
        },
        /**
         * 保存菜式
         */
        submitNewCar() {
            this.foodVisible = false;
            this.addForm.mealList[this.activeInx].foods = [];

            this.selected.forEach(item => {
                this.addForm.mealList[this.activeInx].foods.push({
                    name: item.name,
                    menu_id: item.id,
                    price: item.price,
                    path: item.path
                })
            })

            if (this.addForm.mealList[this.activeInx].foods.length > 20) {
                this.addForm.mealList[this.activeInx].foods.length = 20;
            }

            this.$refs.multipleTable.clearSelection(); // 清空用户的选择，否则会保留之前的选择
        },
        checkSelectable(row) {
            // console.log(this.selected.length)
            if (this.nonCheck) {
                return false;
            } else {
                return true;
            }
        },
        /**
         * 关闭弹窗
         */
        cancelForm() {
            this.foodVisible = false;
        },
        /**
         * 删除菜式
         */
        delFood(val, inx) {
            this.addForm.mealList[val].foods.splice(inx, 1);
        },
        /**
         * 添加餐次
         */
        addMeal() {
            this.addForm.mealList.push({
                id: undefined,
                name: undefined,
                foods: []
            })
        },
        /**
         * 删除餐次
         */
        delMeal(inx) {
            this.addForm.mealList.splice(inx, 1);
        },
        /**
         * 保存菜单
         */
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.idEdit) {
                        let yes = (res => {
                            this.saveInfo();
                        })
                        let cancel = (res => {
                            this.resetForm();
                        })

                        this.e_confirm({yes: yes, cancel: cancel, txt: '是否要保存菜单信息修改?'});
                    } else {
                        this.saveInfo();
                    }
                } else {
                    return false;
                }
            })
        },
        saveInfo() {
            this.loading.status = true;
            let menus = [];

            this.addForm.mealList.forEach(item => {
                let ids = [];

                item.foods.forEach(val => {
                    ids.push(val.menu_id)
                })

                menus.push({
                    id: item.id,
                    name: item.name,
                    menu_id: ids
                })
            })

            let params = {
                menus,
                day_time: this.addForm.dayTime
            }

            const success = (res => {
                this.$message.success(res.msg);
                this.resetForm();
            })
            const fail = (res => {
                this.loading.status = false;

                if (Array.isArray(res.msg)) {
                    let str = res.msg.join('<p style="padding-top: 10px"></p>');

                    this.$message({
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                        message: str
                    });
                } else {
                    this.$message.error(res.msg);
                }
            })

            if (this.idEdit) {
                params.id = this.meunId;
                this.$ajax.put("api/carte/single", params, {func: {success: success, fail: fail}});
            } else {
                this.$ajax.post("api/carte/single", params, {func: {success: success, fail: fail}});
            }
        },
        /**
         * 返回上一级
         */
        resetForm() {
            this.$router.go(-1);
        },
        /**
             * row里面有id作为唯一标识
             */
            getRowKeys(row) {
                return row.id;
            },
        /**
         * 列表数据多选
         * @param {Array} val 选中数据的数组
         */
        tableSelectionChange(val) {
            this.selected = val;
        },
        /**
         * 设置每页列表的数量
         * @param {Number} val 每页数据条数
         */
        setCurrentSize(val) {
            this.listParam.pageIndex = 1;
            this.listParam.pageSize = val;

            this.getFood();
        },
        /**
         * 设置当前列表的页数
         * @param {Number} val 页数
         */
        setCurrentPage(val) {
            this.listParam.pageIndex = val;

            this.getFood();
        },
    },
}
</script>

<style lang="scss">
.publish-menu {
    padding-top: 20px;

    .food-manage {
        .el-dialog__body {
            padding-bottom: 40px;
        }

        .food-content-head {
            .search-text {
                display: flex;
                margin: 20px 0;

                >div:first-child {
                    width: 160px;
                }

                >div:nth-child(2) {
                    margin: 0 20px;
                    width: 160px;
                }
            }
        }
    }

    

    .publish-container {
        .add-food {
            .el-form-item__content {
                display: flex;
                flex-wrap: wrap;
            }
        }

        .el-form-item__content {
            .list-box {
                position: relative;
                margin-right: 20px;
                margin-bottom: 22px;
                width: 260px;
                height: 240px;
                line-height: normal;
                border: 1px solid #DDDDDD;
                box-sizing: border-box;

                img {
                    width: 100%;
                    height: 160px;
                    min-height: 160px;
                    object-fit: contain;
                }

                span:nth-child(2) {
                    display: block;
                    padding: 16px 0 12px 12px;
                    font-size: 14px;
                    color: #000000;
                }

                span:nth-child(3) {
                    padding-left: 12px;
                    font-size: 12px;
                    color: #333333;
                }

                .food-del-btn {
                    position: absolute;
                    display: none;
                }
            }

            .list-box:hover .food-del-btn{
                display: block;
                top: 8px;
                right: 8px;
                color: #fff;
                font-size: 22px;
                border-radius: 50%;
                box-shadow: 0 0 1px 2px #000;
                cursor: pointer;
            }

            .list-box:nth-child(3n) {
                margin-right: 0;
            }

            .add-food-box {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 260px;
                height: 240px;
                border: 1px dotted #DDDDDD;
                box-sizing: border-box; 
                cursor: pointer;  

                i {
                    font-size: 64px;
                    color: #ddd;
                }
            }
        }

        .add-meal {
            display: inline-block;
            margin-top: 22px;
            margin-bottom: 40px;
            width: 108px;
            height: 36px;
            line-height: 36px;
            font-size: 14px;
            text-align: center;
            color: #348EFC;
            border: 1px solid #348EFC;
            border-radius: 2px;
            cursor: pointer;
            box-sizing: border-box;

            i {
                margin-right: 4px;
            }
        }
    }
}
</style>